# -*- coding: utf-8 -*-

# Copyright (c) 2011, Sergey Karakovskiy, Nikolay Sohryakov
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#     * Redistributions of source code must retain the above copyright
#       notice, this list of conditions and the following disclaimer.
#     * Redistributions in binary form must reproduce the above copyright
#       notice, this list of conditions and the following disclaimer in the
#       documentation and/or other materials provided with the distribution.
#     * Neither the name of Yasker nor the
#       names of its contributors may be used to endorse or promote products
#       derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
# BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from Queue import Queue
import json
import logging
import threading
from PyQt4 import QtGui, QtCore
import os
from PyQt4.QtCore import SIGNAL, QUrl, QTimer
from PyQt4.QtGui import QMainWindow
from PyQt4.QtWebKit import QWebSettings
from ui.MainWindow import Ui_MainWindow
from util import settings
import yasker_core
from Keys import *;

__author__ = 'Sergey Karakovskiy, Nikolay Sohryakov'
__copyright__ = 'Copyright 2011, Yasker'
__license__ = 'New BSD'
__email__ = 'Nikolay.Sohryakov+yasker@gmail.com, Sergey.Karakovskiy+yasker@gmail.com'

class MainWindow(QMainWindow):
	templates_path = os.path.join(os.getcwd(), 'resources', 'templates')

	def __init__(self):
		QtGui.QWidget.__init__(self)

		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		#TODO: add startup option for this feature
		QWebSettings.globalSettings().setAttribute(
			QWebSettings.DeveloperExtrasEnabled, True)

		self._events_timer = QTimer(self)

		#		SIGNALS:
		self.connect(self.ui.webView_UI.page().mainFrame(),
		             SIGNAL('javaScriptWindowObjectCleared()'),
		             self.jsWindowObjectCleared)
		self.connect(self.ui.webView_UI, SIGNAL('loadFinished( bool )'),
		             self.webView_UI_post_load)
		self.connect(self._events_timer, SIGNAL('timeout()'),
		             self.tick_updates)

		self.showLoginPage()

		QtCore.QCoreApplication.setApplicationName('Yasker')
		QtCore.QCoreApplication.setOrganizationName('The Yasker Team')
		self._events_queue = Queue()
		yasker_core.init_core(self._events_queue)


	def tick_updates(self):
		while not self._events_queue.empty():
			event = self._events_queue.get(False)
			self.handle_events(event)
			self._events_queue.task_done()

	def handle_events(self, event):
		"""
		Process updates/events according to the code.

		Event is a tuple (event_code, details).
		"""
		event_code = event[0]
		#		logging.debug(event)
		if event_code == yasker_core.Events.ADD_PROJECT:
			project_dict = event[1]
			project_dict[DESCRIPTION] = project_dict['description'].replace('\n','\\n')
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript(
				"""addProject('%s')""" % json.dumps(project_dict))
		elif event_code == yasker_core.Events.ADD_TASK:
			task_dict = event[1]
			if task_dict[TASK_PARENT] is None:
				task_dict[TASK_PARENT] = ""
				addFunction = "addRootTask('%s')"
			else:
				addFunction = "addSubTask('%s')"
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript(addFunction
			% json.dumps(task_dict))

	@QtCore.pyqtSlot()
	def load_projects(self):
		"""
		Load projects list and display them
		"""
		#TODO:
		projects_list = yasker_core.get_all_projects()
		for project in projects_list:
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript("""
				addProject('%s')
			""" % json.dumps(project))

	@QtCore.pyqtSlot(str)
	def load_root_tasks(self, p_id):
		"""
		Get tasks list for the selected project and display them.
		"""
		tasks = yasker_core.get_root_tasks(str(p_id))
		for task in tasks:
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript("""
				addRootTask('%s')
			""" % json.dumps(task))

	@QtCore.pyqtSlot(str)
	def load_sub_tasks(self,  t_id):
		"""
		Load subtasks
		"""
		tasks = yasker_core.get_sub_tasks(str(t_id))
		for task in tasks:
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript("""
				addSubTask('%s')
			""" % json.dumps(task))

	@QtCore.pyqtSlot(str)
	def create_task(self, task_details_json):
		print task_details_json
		task_details_dict = json.loads(str(task_details_json))
		yasker_core.create_task(task_details_dict)

	@QtCore.pyqtSlot()
	def login(self):
		"""
		A function to handle a login process.

		This function is called when user presses a submit button.
		This function is available only for and from the login page.
		"""
		frame = self.ui.webView_UI.page().mainFrame()
		jid = frame.findFirstElement('#jid').evaluateJavaScript(
			'this.value').toString()
		pwd = frame.findFirstElement('#pwd').evaluateJavaScript(
			'this.value').toString()
		is_save_cred = frame.findFirstElement('#save_cred').evaluateJavaScript(
			'this.checked')
		is_save_cred = str(is_save_cred.toString()) == 'true'
		is_auto_login = str(
			frame.findFirstElement('#auto_login').evaluateJavaScript(
				'this.checked').toString()) == 'true'
		if yasker_core.core.login(str(jid), str(pwd)):
			#TODO: load user settings
			yasker_core.core.init_storage(str(jid))
			yasker_core.core.process_credentials(jid, pwd, is_save_cred,
			                                     is_auto_login)
			# no need to store credential as a plain text anymore
			del pwd
			del jid
			self.ui.webView_UI.setUrl(QUrl("qrc:/ui.html"))
			self._events_timer.start(100)

	def webView_UI_post_load(self, is_ok):
		url = str(self.ui.webView_UI.url().toString())
		if url == 'qrc:/login.html':
			jid, pwd, is_auto_login = settings.getCredentials()
			self.ui.webView_UI.page().mainFrame().evaluateJavaScript("""
				var jid = document.getElementById("jid");
				if (jid) {
					jid.value = "%s";
				}
				var pwd = document.getElementById("pwd");
				if (pwd) {
					pwd.value = "%s";
				}
				var auto_login = document.getElementById("auto_login");
				auto_login.checked = %s;
			""" % (jid, pwd, is_auto_login))
			del jid
			del pwd
			if is_auto_login:
				self.login()
		elif url == 'qrc:/ui.html':
			self.load_projects()

	@QtCore.pyqtSlot(str)
	def create_project(self, project_details_json):
		print str(project_details_json)
		project_details_dict = json.loads(str(project_details_json))
		yasker_core.create_project(project_details_dict)

	def showLoginPage(self):
		self.ui.webView_UI.setUrl(QUrl('qrc:/login.html'))

	def jsWindowObjectCleared(self):
		"""
		Encapsulates a Python class into the web page.
		"""
		frame = self.ui.webView_UI.page().mainFrame()
		frame.addToJavaScriptWindowObject('pyForm', self)
